//
//  STWrite.swift
//  TTCOM-iOS
//
//  Created by Toj on 4/10/23.
//

import Foundation

public class STWrite: NSObject {
    public static let shared = STWrite()
    
    private var filePath: NSString = ""
    public func setupFilePath() {
        let document =  NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first ?? ""
        if document.isEmpty { return }
        filePath = document.to_cocoaString.appendingPathComponent("ST").to_cocoaString.appendingPathComponent("Logs/st.log").to_cocoaString 
        print("-->toj: \(filePath)")
    }
    
    public func write(log: String) {
        let fileManager = FileManager.default
        if !fileManager.fileExists(atPath: filePath.to_string) {
            // 如果不存在,则说明是第一次运行这个程序，那么建立这个文件夹
            let directoryPath = filePath.deletingLastPathComponent
            try? fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true)
            try? log.write(toFile:filePath.to_string, atomically: true, encoding: .utf8)
            return
        }
      
        let fileHandle = FileHandle(forUpdatingAtPath: filePath.to_string)
        fileHandle?.seekToEndOfFile()
        guard let data = log.to_data else { return }
        fileHandle?.write(data) // 追加写入数据
        fileHandle?.closeFile()
    }
}
